﻿using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using DDDEF.Application;
using DDDEF.Domain.Services;
using DDDEF.Infrastructure;
using DDDEF.Infrastructure.Caching;
using DDDEF.Infrastructure.Data;
using System.Configuration;
using System.Reflection;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace DDDEF.Presentation
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            ContainerBuilder builder = new ContainerBuilder();
            
            // 缓存
            builder.RegisterType<MemoryCacheManager>().As<IStaticCacheManager>().SingleInstance();

            // 服务
            builder.RegisterType<MusicAppService>().As<IMusicAppService>().InstancePerLifetimeScope();
            builder.RegisterType<MusicService>().As<IMusicService>().InstancePerLifetimeScope();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());


            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AsImplementedInterfaces();
            //repositories
            builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

            // 数据库上下文
            builder.Register<IDbContext>(w => new DDDEFContext(ConfigurationManager.ConnectionStrings["DDDEFContext"].ToString())).InstancePerLifetimeScope();

          

            var container = builder.Build();

            var webApiResolver = new AutofacWebApiDependencyResolver(container);

            GlobalConfiguration.Configuration.DependencyResolver = webApiResolver;

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}
